package handler;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.text.ParseException;
import java.util.Arrays;
import java.util.Date;
import java.util.List;
import java.util.Objects;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.json.JSONObject;

import pojo.bean.EmailUser;
import pojo.bean.EmailUserPage;
import pojo.dao.EmailUserDAO;
import pojo.mapper.EmailUserMapper;
import tool.JSONObjectConverter;
import tool.MapperGenerator;

public class DataGridRequestHandler extends HttpServlet {
    private static final long serialVersionUID = -1742388344114399894L;
    private EmailUserMapper emailUserMapper;

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        String operation = req.getParameter("operation");
        switch (operation) {
        case "selectByPrimaryKey":
            int identifier = Integer.parseInt(req.getParameter("identifier"));
            if (identifier == 0) {
                return;
            }
            EmailUser emailUser = emailUserMapper.selectByPrimaryKey(identifier);
            JSONObject object = JSONObjectConverter.convert(emailUser);
            System.out.println(object);
            resp.getWriter().print(object);
            break;
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");
        resp.setContentType("application/json;charset=UTF-8");
        String operation = req.getParameter("operation");
        switch (operation) {
        case "selectByKeyword":
            String keyword = Objects.nonNull(req.getParameter("keyword")) ? req.getParameter("keyword") : "";
            int recordsCount = emailUserMapper.selectCountByUserNameKeyword(keyword);
            int pageNumber = Integer.parseInt(req.getParameter("page"));
            int pageSize = Integer.parseInt(req.getParameter("rows"));
            // 构建一个页面实例
            EmailUserPage page = new EmailUserPage(pageNumber, pageSize);
            page.setRecordsCount(recordsCount);
            // 构建一个用于执行查询的临时邮件用户实例
            EmailUser condition = new EmailUser(keyword);
            // 设置临时邮件用户为页面的条件
            page.setCondition(condition);
            List<EmailUser> elements = emailUserMapper.selectByUserNameKeyword(page);
            // 构建一个用于存放JSON对象的有序集合
            List<JSONObject> objects = page.getRecords();
            objects = JSONObjectConverter.convert(elements);
            page.setRecords(objects);
            JSONObject object = new JSONObject(page);
            resp.getWriter().print(object);
            break;
        case "update":
            int identifier = Integer.parseInt(req.getParameter("identifier"));
            String userName = req.getParameter("userName");
            int age = Integer.parseInt(req.getParameter("age"));
            String email = req.getParameter("email");
            Date registrationTime = null;
            try {
                registrationTime = JSONObjectConverter.DATE_FORMAT.parse(req.getParameter("registrationTime"));
            } catch (ParseException e) {
                e.printStackTrace();
            }
            EmailUser temporary = new EmailUser(identifier, userName, age, email, registrationTime);
            emailUserMapper.updateByPrimaryKey(temporary);
            break;
        case "remove":
            String identifiers = req.getParameter("identifiers");
            if (Objects.nonNull(identifiers) && identifiers.length() > 0) {
                String[] arr = identifiers.split(",");
                List<String> list = Arrays.asList(arr);
                emailUserMapper.deleteByPrimaryKeys(list);
            }
        }
    }

    @Override
    public void init() throws ServletException {
        try {
            emailUserMapper = MapperGenerator.generate(EmailUserDAO.class);
        } catch (NoSuchMethodException | SecurityException | InstantiationException | IllegalAccessException
            | IllegalArgumentException | InvocationTargetException e) {
            e.printStackTrace();
        }
        super.init();
    }

}
